<!--
/**
 * Created by PhpStorm.
 * User: Devmc
 * Date: 2021/4/24
 * Time: 1:20
 */
-->
<template>
  <el-dialog
      :title="titles[0]"
      :center="true"
      :destroy-on-close="true"
      :append-to-body="true"
      :visible.sync="dialogVisible"
      width="640px">

    <el-transfer
        v-model="value"
        :data="data"
        :titles="[titles[1], titles[2]]"
        :filterable="search"
        @change="onChange"
        style="margin: 0 auto; display: table; width: 650px">
    </el-transfer>

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="onConfirm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: "Transfer",
  props: {
    idKey: {
      type: String,
      default: 'id'
    },
    labelKey: String,
    search: {
      type: Boolean,
      default: true
    },
    // 大 左 右
    titles: {
      type: Array,
      default: () => {
        return ['选择人员', '列表一', '列表二'];
      }
    },

    // 可选择的人数
    num: {
      type: Number,
      default: 0
    },
  },
  data() {
    return {
      dialogVisible: false,

      data: [],
      value: [],

      promise: null
    };
  },
  created() {

  },
  mounted() {

  },
  methods: {
    /**
     * 打开选择
     */
    transform(users, values) {
      this.data = this.generateData(users);
      this.value = values;
      this.dialogVisible = true;

      return new Promise((resolve => {
        this.promise = resolve;
      }));
    },

    /**
     * 确定
     */
    onConfirm() {
      this.promise && this.promise(this.value);
      this.dialogVisible = false;
    },

    /**
     * 监听变化
     * 处理只选择一个人
     */
    onChange(keys, where) {
      if (this.num != 0) {
        if (where == 'right') {
          this.value = this.value.filter((item, index) => {
            return index < this.num;
          })
        }
      }
    },


    /**
     * 处理数据
     *
     * @return {*[]}
     */
    generateData(users) {
      const data = [];

      users.forEach((item) => {
        data.push({
          key: item[this.idKey],
          label: item[this.labelKey]
        });
      });
      return data;
    }
  },
  watch: {}
}
</script>

<style lang="scss">

</style>